<?php
require('SendSms.php');

$goods = $_POST['goods'];
$name = $_POST['name'];
$uid = $_POST['uid'];
$phone = $_POST['phone'];
$sf = $_POST['sf'];
$city = $_POST['city'];
$xian = $_POST['xian'];
$dizhi = $_POST['dizhi'];
$oderid = $_POST['oderid'];
$time = $_POST['time'];
$channel = $_POST['channel'];
$price = $_POST['price'];
$beizhu = "已经提交运营商审核";

include_once("../untils/conn.php");

if ($con) {
    mysqli_query($con, "set names utf8");

    // 判断是否有name，uid，phone，dizhi这四项信息，如果有任何一项为空，则返回错误信息
    if (empty($name) || empty($uid) || empty($phone) || empty($dizhi)) {
        $response = array('status' => -1, 'msg' => '信息不完整，请重新输入');
        echo json_encode($response);
        return;
    }

    // 判断订单是否已经提交过
    session_start();
    if (isset($_SESSION['order_id']) && $_SESSION['order_id'] == $oderid) {
        $response = array('status' => 1, 'msg' => '订单已经提交过了');
        echo json_encode($response);
        return;
    }

    $data_query = mysqli_query($con, "select * from oder where uid='$uid'");
    $count = mysqli_num_rows($data_query);

    if ($count > 10) {
        // 用户已经申请过了，返回状态码1和提示信息
        $response = array('status' => 1, 'msg' => '您申请的订单已超限，请联系客服');
        echo json_encode($response);
    } else {
        // 判断$channel变量是否为空，如果为空则将其赋值为null
        if (empty($channel)) {
            $channel = 0;
        }
        $data_insert = mysqli_query($con, "insert into oder(goods,name,uid,phone,sf,city,xian,dizhi,oderid,time,price,channel) values('$goods','$name','$uid','$phone','$sf','$city','$xian','$dizhi','$oderid','$time','$price','$channel')");
            
            if ($data_insert) {
            $sql = "SELECT haokaid FROM list WHERE name='$goods'";
                        $res = mysqli_query($con, $sql);
            if (mysqli_num_rows($res) > 0) {
                $row = mysqli_fetch_assoc($res);
                $haokaid = $row['haokaid'];
            }

            $sql = "SELECT * FROM config_api WHERE groups = 'haokeyun'";
            $res = mysqli_query($con, $sql);
            if (mysqli_num_rows($res) > 0) {
                $row = mysqli_fetch_assoc($res);
                $userid = $row['userid'];
                $token = $row['token'];
                $gdkey = $row['gdkey'];
            }

            // 拼装高德地图接口URL
            $address = urlencode($sf . $city . $xian . $dizhi);
            $url = "https://restapi.amap.com/v3/geocode/geo?key=$gdkey&address=$address&city=";

            // 发送请求获取城市编码
            $response = file_get_contents($url);
            $data = json_decode($response, true);

            if ($data['status'] == "1" && $data['count'] > 0) {
                $citycode = $data['geocodes'][0]['citycode'];
                $address_code = $citycode;
            } else {
                $response = array('status' => -4, 'msg' => '没有符合的地区编码~');
                echo json_encode($response);
            }
            
            function buildSign($param, $token)
            {
                ksort($param);
                $arr = [];
                foreach ($param as $k => $v) {
                    $arr[] = $k . "=" . $v;
                }
                $str = join(";", $arr);
                $str .= $token;
                $sign = strtoupper(md5($str));
                return $sign;
            }
            
            // 构造请求参数
            $params = array(
                'userId' => $userid,
                'goodsCode' => $haokaid,
                'orderSn' => $oderid,
                'cusName' => $name,
                'cusPhone' => $phone,
                'cusIdno' => $uid,
                'consignee' => $name,
                'province' => $sf,
                'city' => $city,
                'district' => $xian,
                'address_code' => $address_code,
                'address' => $dizhi,
                
            );
            
            // 计算签名
           $sign = buildSign($params, $token);
            
            // 添加签名到请求参数
            $params['sign'] = $sign;
            
            // 构造请求头
            $headers = array(
                'Content-Type: application/json'
            );
            
            // 发送请求
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://haokeyun.vip/api/outside/order/submit_order');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);
            
            // echo "data：" . $response . "\n";
            // exit;


            
            // 解析响应数据
            $result = json_decode($response, true);

            if ($result['code'] == 200) {
                // 更新订单状态
                $update_sql = "UPDATE oder SET status=1, beizhu='$beizhu' WHERE oderid='$oderid'";
                $update_query = mysqli_query($con, $update_sql);

                if ($update_query) {
                    // 更新成功，返回状态码0和提示信息
                    $response = array('status' => 0, 'msg' => '申请成功');
                    echo json_encode($response);
                    // 将订单号写入session
                    $_SESSION['order_id'] = $oderid;

                    //发送短信通知
                    sendSms($appId, $appKey, $phoneNumber, $templateId, $smsSign);
                } else {
                    // 更新失败，返回状态码-2和提示信息
                    $response = array('status' => -2, 'msg' => '更新订单状态失败');
                    echo json_encode($response);
                }
            } else {
                // 下单失败，返回接口返回的错误信息
                $response = array('status' => $result['code'], 'msg' => $result['message']);
                echo json_encode($response);
            }

        } else {
            // 信息不全，返回状态码-1和提示信息
            $response = array('status' => -1, 'msg' => '哦豁，又出错了，找客服吧~');
            echo json_encode($response);
        }
    }
}
